package com.habdqn.easybuy.service.impl;

import com.habdqn.easybuy.dao.NewsDao;
import com.habdqn.easybuy.dao.UserDao;
import com.habdqn.easybuy.dao.impl.NewsDaoImpl;
import com.habdqn.easybuy.dao.impl.UserDaoImpl;
import com.habdqn.easybuy.entity.News;
import com.habdqn.easybuy.service.NewsService;
import com.habdqn.easybuy.util.Page;

import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28
 */
public class NewsServiceImpl implements NewsService {
    private NewsDao newsDao = new NewsDaoImpl();
    private UserDao userDao = new UserDaoImpl();

    @Override
    public News queryById(Integer id) {
        return newsDao.queryById(id);
    }

    /**
     * 查询所有新闻
     *
     * @return 所有新闻
     */
    @Override
    public List<News> queryAll() {
        return newsDao.queryAll(null,null);
    }

    @Override
    public Page<News> queryByPageWithUser(News condition, Page<News> page) {
        // 获取分页集合
        page.setRows(newsDao.queryAll(condition, page));
        // 组装关联用户对象
        page.getRows().forEach((news -> {
            if (news.getUserId() != null && news.getUserId() > 0) {
                news.setAuthor(userDao.queryById(news.getUserId()));
            }
        }));
        // 获取总记录数
        page.setTotal(newsDao.getTotal(condition));
        return page;
    }

    @Override
    public News insert(News news) {
        news.setId(newsDao.insert(news));
        return news;
    }

    @Override
    public News update(News news) {
        if (newsDao.update(news) > 0) {
            return news;
        }
        return null;
    }

    @Override
    public boolean deleteById(Integer id) {
        return newsDao.deleteById(id) > 0;
    }
}
